package cn.rjzjh.commons.util.apiext;

import java.util.Map;
import java.util.Properties;

import org.apache.commons.lang3.StringUtils;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import cn.rjzjh.commons.util.Conf;
import cn.rjzjh.commons.util.exception.ProjectException;

public class RedisClient {
	public static final String REDISENVNAME = "redisname";
	private static JedisPool jedisPool;// 非切片连接池

	private final static Object lockObj = new Object();

	/****
	 * 通过配置得到 Jedis
	 *
	 * @param connProp
	 * @return
	 * @throws ProjectException
	 */
	public static Jedis getConnection(Properties connProp) {
		if (connProp == null || connProp.size() == 0) {
			return null;
		}
		if (jedisPool == null) {
			synchronized (lockObj) {
				String redisName = System.getenv(REDISENVNAME);
				if (StringUtils.isBlank(redisName)) {
					redisName = "default";
				}
				String appName = (String) connProp.get(String.format(
						"redisname_%s", redisName));
				Map<String, String> confMap = Conf.getRedisServerPropByKey(
						connProp, appName);
				JedisPoolConfig config = new JedisPoolConfig();
				config.setMaxTotal(Integer.parseInt(confMap.get("maxTotal")));
				config.setMaxIdle(Integer.parseInt(confMap.get("maxIdle")));
				config.setMaxWaitMillis(Integer.parseInt(confMap
						.get("maxWaitMillis")));
				config.setTestOnBorrow(Boolean.parseBoolean(confMap
						.get("testOnBorrow")));

				String password = confMap.get("password");
				if (StringUtils.isBlank(password)) {// 有设置密码
					jedisPool = new JedisPool(config, confMap.get("host"),
							Integer.parseInt(confMap.get("port")));
				} else {
					jedisPool = new JedisPool(config, confMap.get("host"),
							Integer.parseInt(confMap.get("port")),
							Integer.parseInt(confMap.get("maxIdle")), password);
				}

			}
		}
		return jedisPool.getResource();
	}

	/***
	 * 放资源
	 *
	 * @param jedis
	 */
	public static void returnResource(Jedis jedis) {
		if (jedisPool != null) {
			jedisPool.returnResource(jedis);
		}
	}

}
